import LyRequest from '@/service/request/request'
import { ReLoginStatus, ResultStatus, TOKEN } from '@/global/constant'
import { ElLoading, ElNotification } from 'element-plus'
import router from '@/router'
import { localCache } from '@/utils/cache'
import { useAccountStore, useGlobalStore } from '@/store'

const lyRequest = new LyRequest({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: import.meta.env.VITE_TIME_OUT,
  withCredentials: true,
  interceptors: {
    // 请求拦截器
    requestSuccessFn: (config) => {
      // 给请求头加上token
      const token = localCache.getCache(TOKEN) ?? {}
      config.headers && (config.headers[token.name] = token.value)
      // 有些请求有loading效果
      config.isShowLoading && ElLoading.service({ text: '加载中...' })
      return config
    },
    requestFailureFn: (err) => {
      return Promise.reject(err)
    },
    // 响应拦截器
    responseSuccessFn: (res) => {
      const accountStore = useAccountStore()
      const globalStore = useGlobalStore()
      if (res.data.code === ResultStatus.SUCCESS) {
        return res.data
      } else if (Object.values(ReLoginStatus).includes(res.data.code)) {
        // 上面的判断条件是找到要重新登录的状态码
        // token过期，重新登陆
        ElNotification.error(res.data.msg || '出错，请重新登录')
        globalStore.cleanLocalUserInfo()
        router.push('/login')
      } else if (
        ResultStatus.CODE_INVALID === res.data.code ||
        ResultStatus.NAME_OR_PWD_ERR === res.data.code
      ) {
        ElNotification.error(res.data.msg)
        // 验证码错误或者登录失败就重新请求验证码
        accountStore.getVerifyCodeAction()
        return res.data
      } else {
        // 加上element-ui提示
        ElNotification({
          type: 'error',
          message: res.data.msg || '服务器出错',
          duration: 2500
        })
        return Promise.reject(res.data.msg || '服务器出错')
      }
    },
    responseFailureFn: (err) => {
      console.log(err)
    }
  }
})

export default lyRequest
